/*
SEVERANCE PAY

Data 	: 
Folder 	: 
Date	: 2018-03-11

Creator		: Jonas Cederlof	(JC)
Description : 
Notes:


LATEST UPDATE: 	2018-03-28

*/

********************************************************************************

clear
set more		 off
cap   log close 	_all

log using 	"../log/B2_severance.log"	, replace 
use 		 "$datapath/A3_age55data_WC.dta"


{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
local Cstyle "ms(oh) mcolor(black) lcolor(black) lpattern(dash)"
local Sstyle "lpattern(shortdash_dot) lcolor(gray) vertical" 

{ // Generate: Event time to displacement
*===============================================================================
bys lopnr (date) : gen lastmonthwork =  date if  atfirm2[_n-1]==1 & atfirm2==1 & atfirm2[_n+1]==0  & atfirm2[_n+2]==0 
format lastmonthwork %tm

bys lopnr (date) : gen nvals = sum(1) 	if lastmonthwork!=.
tab nvals 				if lastmonthwork!=.
bys lopnr : egen maxnvals = max(nvals)

*Take away displacemnt dates that occur 12 months before notification for those with multiple displacments dates
replace lastmonthwork=. if eventtime_def<-12 & maxnvals>1


bys lopnr (date) : gen nvals2 = sum(1) 	if lastmonthwork!=.
tab nvals2 				if lastmonthwork!=.
bys lopnr : egen maxnvals2 = max(nvals2)
*Now 93.87 percent are displaced only once

 gen diff = lastmonthwork - notdate_def
 tab diff treat 
*So very few do not work 12 months prior to notification so we get rid of these
replace lastmonthwork=. if eventtime_def<-12
drop diff
gen diff = lastmonthwork - notdate_def
 tab diff treat 
   

   
*Taking the minimum date assures that we get the nvals==1 as displacement date
fastmin lastmonthwork , by(lopnr) name(dispdate)
replace dispdate = dispdate +1
format dispdate %tm


*Recalls (working 3 months after displacement event has occured)
bys lopnr (date) : gen xrecalldate = date if atfirm2[_n-2]==0 & atfirm2[_n-1]==0 & atfirm2==1 & atfirm2[_n+1]==1 & atfirm2[_n+3]==1 & date>dispdate
fastmin xrecalldate , by(lopnr) name(recalldate)
format recalldate %tm
drop x*
gen recalled = recalldate!=.   
   
*Generate: Month of displacement
gen monthofdisp = month(dofm(dispdate))

*Generate: Months worked after notification
gen RAMSmonths = dispdate - notdate_def


*Generate: Displacement event time
bys lopnr (date) : gen dispeventtime = date - dispdate


}
*
merge m:1 lopnr dispeventtime using "$datapath/SP.dta"
drop if _merge==2
drop _merge

{ // RD graphs of Severance Pay 
*===============================================================================

*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"

local Y "SP5_win_1_99"

*Raw severance
preserve
	keep if  dispeventtime==0 
	*keep if tenureatnot>=120
	replace `Y' = `Y'/1000
	*keep if maxnvals2==1
	*winsor2 SP5, c(5 95) replace	
	xtreg 	`Y' 	$instrument  $linear $covariets, cluster(varselid) fe nonest
	local bSP  = round(_b[treat],.001)
	*local bSP : di %9.2f `bSP' 
	local seSP = round(_se[treat],.001)
	*local seSP : di %9.2f `seSP' 


	*Residulize year*moth fixed effects
	areg `Y' $covariets if e(sample)==1 ,absorb(ym_def)
	predict e, residuals
	sum `Y' 
	replace `Y' = e + r(mean) if e(sample)==1
	
	
	gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `Y'_bin = mean(`Y')
	*tab runvar bin
	

	gen freq=1

	collapse (mean) `Y' `Y'_bin  (sum) freq, by(runvar  bin treat )
	replace runvar = runvar*12

	twoway 	(scatter  `Y'_bin bin , ms(o) mcolor(black)) ///
		(lfit `Y' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
		(lfit `Y' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
	, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
	graphregion(color(white)) xtitle("Normalized age (months)") ytitle("Severance pay (1,000 SEK)") ///
	text(133 -19   "{&beta}=`bSP'**" "(`seSP')"  ,place(right)  ) ///
	legend(off) yscale(r(100 140)) ylab(100(10)140)
	*note("Note: b=`bSP' , se=`seSP'")
	
	
	graph export "$agegraphpath/RD/RD_`Y'.pdf", replace
restore	



}
*
{ // DOUNT RD graphs of Severance Pay 
*===============================================================================

*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"

local Y "SP5_win_1_99"

*Raw severance
preserve
	keep if  dispeventtime==0 
	gen temp =round(runvar*12)
	drop if inrange(temp,-3,3)
	*keep if tenureatnot>=120
	replace `Y' = `Y'/1000
	*keep if maxnvals2==1
	*winsor2 SP5, c(5 95) replace	
	xtreg 	`Y' 	$instrument  $linear $covariets, cluster(varselid) fe nonest
	local bSP  = round(_b[treat],.001)
	*local bSP : di %9.2f `bSP' 
	local seSP = round(_se[treat],.001)
	*local seSP : di %9.2f `seSP' 


	*Residulize year*moth fixed effects
	areg `Y' $covariets if e(sample)==1 ,absorb(ym_def)
	predict e, residuals
	sum `Y' 
	replace `Y' = e + r(mean) if e(sample)==1
	
	
	*gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `Y'_bin = mean(`Y')
	*tab runvar bin
	

	gen freq=1

	collapse (mean) `Y' `Y'_bin  (sum) freq, by(runvar  bin treat )
	replace runvar = runvar*12

	twoway 	(scatter  `Y'_bin bin , ms(o) mcolor(black)) ///
		(lfit `Y' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
		(lfit `Y' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
	, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
	graphregion(color(white)) xtitle("Normalized age (months)") ytitle("Severance pay (1,000 SEK)") ///
	text(133 -19   "{&beta}=`bSP'**" "(`seSP')"  ,place(right)  ) ///
	legend(off) yscale(r(100 140)) ylab(100(10)140)
	*note("Note: b=`bSP' , se=`seSP'")
	
	
	graph export "$agegraphpath/RD/RD_`Y'.pdf", replace
restore	



}
*

{ // Event graph of Severance Pay 		(People displaced in Januray)
*===============================================================================
preserve

*Generate: Total wages from all firms (notifying + other) in each month
egen sumwage = rowtotal(monthly_w1 monthly_w2)
replace sumwage = monthly_w1 if dispeventtime<0


local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
*IF YOU WANT TO LOOK AT LAST MONTH WORKED FOR JANUARY ADD & monthofdisp==2 TO THE LINE BELOW
	keep if inrange(dispeventtime,-24,24) & dispeventtime!=. &  monthofdisp==2
	gen freq=1
	collapse (mean) sumwage  (sum) freq, by(dispeventtime)
	replace sumwage= sumwage/1000
	twoway (connected sumwage dispeventtime, `Tstyle')  /// 
	, xline(-.5, lpattern(dash) lcolor(black) lstyle(foreground)) /// 
	graphregion(color(white)) xtitle("Months relative to separation") ytitle("Monthly earnings (1,000 SEK)") /// 
	legend(order( 1 "From all firms" )) xscale(r(-24 24 )) xlab(-24(6)24)
	
	graph export "$agegraphpath/Event/event_DISP_SP_jan.pdf", replace
restore	

}
*
{ // RD graphs of recall
*===============================================================================

*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"

local Y "recalled"

*Raw severance
preserve
	keep if  dispeventtime==0 

	
	xtreg 	`Y' 	$instrument  $linear $covariets, cluster(varselid) fe nonest
	local bSP  = _b[treat]
	local bSP : di %9.2f `bSP' 
	local seSP = _se[treat]
	local seSP : di %9.2f `seSP' 


	*Residulize year*moth fixed effects
	areg `Y' $covariets ,absorb(ym_def)
	predict e, residuals
	sum `Y' 
	replace `Y' = e + r(mean)
	
		gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `Y'_bin = mean(`Y')
	*tab runvar bin
	

	gen freq=1

	collapse (mean) `Y' `Y'_bin  (sum) freq, by(runvar  bin treat )
	replace runvar = runvar*12

	twoway 	(scatter  `Y'_bin bin , ms(o) mcolor(black)) ///
		(lfit `Y' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
		(lfit `Y' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
	, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
	graphregion(color(white)) xtitle("Normalized age at notification (months)") ytitle("Pr(Recall)") ///
	legend(off) 
	
	graph export "$agegraphpath/RD/RD_recall.pdf", replace
restore	



}
*
{ // Severance pay and notification time  by cash constraied firm
*===============================================================================
*inc_NetTurnover = nettoomsattning
*inc_opprofit = rorelseresultat
*bs_cashandbank = kassaochbank
*bs_assetstot = summatillgangar
preserve
	use  year firmid inc_NetTurnover inc_opprofit bs_cashandbank bs_assetstot using "$datapath/balancesheet_restricted.dta",clear
	drop if firmid==.
	
	*Merge on firmsize
	merge 1:1 firmid year using "$datapath/A1_firm_char.dta", keepusing(firm_noemployed_RAMS)
	drop if  _merge==2 
	drop 	 _merge
	
	*Calculate cash constrait 
	gen CC = bs_cashandbank/bs_assetstot
	bys firmid (year) : gen CC_tm1 = bs_cashandbank[_n-1]/bs_assetstot[_n-1]
	bys firmid (year) : gen CC2_tm1 = bs_cashandbank[_n-1]/firm_noemployed_RAMS[_n-1]
	
	*Winsorize cash constraint
	winsor2 CC, c(1 99) replace
	winsor2 CC_tm1, c(1 99) replace
	winsor2 CC2_tm1, c(1 99) replace
	
	keep firmid year CC CC_tm1 CC2_tm1 
	tempfile temp
	save `temp'
restore

*Merge on cash constraint meassure
merge m:1 firmid year using `temp' 
drop if _merge==2


*Generate above in sample mean and median 
foreach var of varlist CC CC_tm1 CC2_tm1 {
	sum `var' if eventtime_def==0,d
	gen xD2mean_`var' = `var'<r(mean) if eventtime_def==0
	gen xD2median_`var' = `var'<r(p50) if eventtime_def==0
	xtile xCCquart_`var' = `var' if eventtime_def==0, nq(4)  

	fastmax xD2mean_`var', name(D2mean_`var') by(lopnr)
	fastmax xD2median_`var', name(D2median_`var') by(lopnr)
	fastmax xCCquart_`var', name(`var'quart) by(lopnr)
}

{ // RD graphs of Severance Pay 
*===============================================================================

*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"


*Raw severance
foreach outvar of varlist SP5_win_1_99 	 {
	if "`outvar'"=="SP5_win_1_99" {
		local outlab "Severance pay (1,000 SEK)"
	}
	else {
		local outlab "Notification time (days)"
	}
	forvalues c = 0(1)1{
		preserve
			replace SP5_win_1_99=SP5_win_1_99/1000
			
			keep if  dispeventtime==0 	
			keep if  D2mean_CC_tm1==`c'
			count
			 xtreg 	`outvar' 	$instrument  $linear $covariets , cluster(varselid) fe nonest
			local bSP  = round(_b[treat],.001)
			*local bSP : di %9.2f `bSP' 
			local seSP = round(_se[treat],.001)
			*local seSP : di %9.2f `seSP' 
			local nSP = e(N)


			*Residulize year*moth fixed effects
			areg `outvar' $covariets ,absorb(ym_def)
			predict e, residuals
			sum `outvar' 
			replace `outvar' = e + r(mean) if e(sample)==1
		
			gen temp =round(runvar*12)
			egen 	bin = cut(temp), at(-36(2)0)
			egen 	bin2 = cut(temp), at(1(2)37)
			replace bin = bin2 if bin==.
			replace bin = bin + .5 
			bys bin: egen `outvar'_bin = mean(`outvar')
			*tab runvar bin
	
			gen freq=1

			collapse (mean) `outvar' `outvar'_bin  (sum) freq, by(runvar  bin treat  )
			replace runvar = runvar*12

			if "`outvar'"=="SP5_win_1_99" {
			twoway 	(scatter  `outvar'_bin bin , ms(o) mcolor(black)) ///
				(lfit `outvar' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
				(lfit `outvar' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
			, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
			graphregion(color(white)) xtitle("Normalized age  (months)") ytitle("`outlab'")  name(a`c',replace) ///
			legend(off) yscale(r(80 160)) ylab(80(20)160) ///
			text(90 3    "{&beta}=`bSP'" "(`seSP')"  ,place(right)  )
			}
			else {
			twoway 	(scatter  `outvar'_bin bin , ms(o) mcolor(black)) ///
				(lfit `outvar' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
				(lfit `outvar' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
			, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
			graphregion(color(white)) xtitle("Normalized age  (months)") ytitle("`outlab'")  name(b`c',replace) ///
			legend(off) ///
			text(90 3   "{&beta}=`bSP'" "(`seSP')"  ,place(right)  )
			}
			graph export "$agegraphpath/RD/RD_`outvar'_CC`c'.pdf", replace
		restore	
	}
}
}
*
{ // RD graphs of Notification time
*===============================================================================
replace nottime_def=nottime_def/30
*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"


*Raw severance
foreach outvar of varlist nottime_def 	 {
	if "`outvar'"=="SP5_win_1_99" {
		local outlab "Severance pay (1,000 SEK)"
	}
	else {
		local outlab "Notification time (months)"
	}
	forvalues c = 0(1)1{
		preserve
			
			
			keep if  dispeventtime==0 	
			keep if  D2mean_CC_tm1==`c'
			count
			 xtreg 	`outvar' 	$instrument  $linear $covariets , cluster(varselid) fe nonest
			local bSP  = round(_b[treat],.001)
			*local bSP : di %9.2f `bSP' 
			local seSP = round(_se[treat],.009)
			*local seSP : di %9.2f `seSP' 
			local nSP = e(N)


			*Residulize year*moth fixed effects
			areg `outvar' $covariets ,absorb(ym_def)
			predict e, residuals
			sum `outvar' 
			replace `outvar' = e + r(mean) if e(sample)==1
		
			gen temp =round(runvar*12)
			egen 	bin = cut(temp), at(-36(2)0)
			egen 	bin2 = cut(temp), at(1(2)37)
			replace bin = bin2 if bin==.
			replace bin = bin + .5 
			bys bin: egen `outvar'_bin = mean(`outvar')
			*tab runvar bin
	
			gen freq=1

			collapse (mean) `outvar' `outvar'_bin  (sum) freq, by(runvar  bin treat  )
			replace runvar = runvar*12

			if "`outvar'"=="SP5_win_1_99" {
			twoway 	(scatter  `outvar'_bin bin , ms(o) mcolor(black)) ///
				(lfit `outvar' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
				(lfit `outvar' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
			, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
			graphregion(color(white)) xtitle("Normalized age  (months)") ytitle("`outlab'")  name(a`c',replace) ///
			legend(off) yscale(r(80 160)) ylab(80(20)160) ///
			text(90 3    "{&beta}=`bSP'" "(`seSP')"  ,place(right)  )
			}
			else {
			twoway 	(scatter  `outvar'_bin bin , ms(o) mcolor(black)) ///
				(lfit `outvar' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
				(lfit `outvar' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
			, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
			graphregion(color(white)) xtitle("Normalized age  (months)") ytitle("`outlab'")  name(b`c',replace) ///
			legend(off) ///
			text(6.6 12   "{&beta}=`bSP'***" "(0`seSP')"  ,place(right)  )
			}
			graph export "$agegraphpath/RD/RD_`outvar'_CC`c'.pdf", replace
		restore	
	}
}

*
}
*

bys lopnr (date) : egen cumatfirm2 	= total(atfirm2==1) 			if inrange(eventtime_def,1,24) 
bys lopnr (date) : egen cumatfirm 	= total(atfirm==1) 			if inrange(eventtime_def,1,24) 

{ // RD graphs of cumulative at firm
*===============================================================================
*replace nottime_def=nottime_def/30
*=========



*
}
*

}
*
log close

/*
{ // RD graphs of Severave Pay by Tenure
*===============================================================================

*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"

local Y "SP5_win_1_99"

*LOW TENURE
preserve
	keep if  dispeventtime==0 
	keep if tenureatnot<60
		
	xtreg 	`Y' 	$instrument  $linear $covariets, cluster(varselid) fe nonest
	local bSP  = _b[treat]
	local bSP : di %9.2f `bSP' 
	local seSP = _se[treat]
	local seSP : di %9.2f `seSP' 
	local N = e(N)


	*Residulize year*moth fixed effects
	areg `Y' $covariets ,absorb(ym_def)
	predict e, residuals
	sum `Y' 
	replace `Y' = e + r(mean)
	
	replace `Y' = `Y'/1000
	gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `Y'_bin = mean(`Y')
	*tab runvar bin
	
	gen freq=1

	collapse (mean) `Y' `Y'_bin  (sum) freq, by(runvar  bin treat )
	replace runvar = runvar*12

	twoway 	(scatter  `Y'_bin bin , ms(o) mcolor(black)) ///
		(lfit `Y' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
		(lfit `Y' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
	, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
	graphregion(color(white)) xtitle("Normalized age at notification (months)") ytitle("Severance Pay (1000 SEK)") ///
	legend(off) name(a,replace) note("N=`N'") subtitle("Tenure < 5 years")
	
	graph export "$agegraphpath/RD/RD_SP_lowtenure.pdf", replace
restore	


*=========
xtset ym_def
*=========
global instrument	"treat"
global linear		"runvar inter"

local Y "SP5_win_1_99"

*HIGH TENURE
preserve
	keep if  dispeventtime==0 
	keep if tenureatnot>=60

	
	
	xtreg 	`Y' 	$instrument  $linear $covariets, cluster(varselid) fe nonest
	local bSP  = _b[treat]
	local bSP : di %9.2f `bSP' 
	local seSP = _se[treat]
	local seSP : di %9.2f `seSP' 
	local N = e(N)


	*Residulize year*moth fixed effects
	areg `Y' $covariets ,absorb(ym_def)
	predict e, residuals
	sum `Y' 
	replace `Y' = e + r(mean)
	
	replace `Y' = `Y'/1000
	gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `Y'_bin = mean(`Y')
	*tab runvar bin
	
	gen freq=1

	collapse (mean) `Y' `Y'_bin  (sum) freq, by(runvar  bin treat )
	replace runvar = runvar*12

	twoway 	(scatter  `Y'_bin bin , ms(o) mcolor(black)) ///
		(lfit `Y' runvar [aweight=freq] if treat==0, lcolor(black) ) ///
		(lfit `Y' runvar [aweight=freq] if treat==1, lcolor(black)  ) ///
	, xline(0, lpattern(dash) lcolor(black) lstyle(foreground))  xlab(-36(12)36) xscale(r(-36 36)) /// 
	graphregion(color(white)) xtitle("Normalized age at notification (months)") ytitle("Severance Pay (1000 SEK)") ///
	legend(off) name(a2,replace) note("N=`N'") subtitle("Tenure {&ge} 5 years")
	
	graph export "$agegraphpath/RD/RD_SP_hightenure.pdf", replace
restore	


*graph combine a a2, col(2) ycommon xcommon graphregion(color(white))
*graph export "../Output2/Age/graphs/RD/RD_SP_by_SP_combine.pdf", replace

}
*


